package com.iking.toolkit.aop;
import com.iking.toolkit.exception.HandlerException;
import com.iking.toolkit.model.Msg;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

/**
 * 同一拦截异常处理类
 * @author lc
 */
@Slf4j
@ControllerAdvice
public class ControllerExceptionAdvice {



    /**
     * 拦截业务校验
     * @param h 手动抛业务异常
     * @return 业务错误返回
     */
    @ExceptionHandler(HandlerException.class)
    @ResponseBody
    public Msg handlerExceptionHandler(HandlerException h){
        log.error(h.getMessage());
        return Msg.fail(h.getMessage());
    }


    /**
     * 统一服务错误处理
     * @param e 异常
     * @return Result
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Msg handle(Exception e) {
        log.error("系统异常:",e);
        return Msg.fail("服务错误");
    }

    /**
     * 拦截参数校验
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public Msg handleConstraintViolationException(ConstraintViolationException exception){
        String msg = exception.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("，", "", ""));
        return Msg.fail(msg);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Msg handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String msg = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("，", "", ""));
        return Msg.fail(msg);
    }
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Msg handleBindException(BindException e){
        String msg = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("，", "", ""));
        return Msg.fail(msg);
    }
}
